package cn.felord.springboot.filters;

import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;

/**
 * The type Abstract filter bean.
 *
 * @author Felordcn
 * @since 11 :19
 */
public abstract class AbstractFilterBean implements OrderedFilter {
    private Set<String> urlPatterns = new LinkedHashSet<>();

    public AbstractFilterBean(String... urlPatterns) {
        Collections.addAll(this.urlPatterns, urlPatterns);
    }

    /**
     * 各自逻辑的函数钩子
     *
     * @param request  the request
     * @param response the response
     */
    public abstract void internalHandler(ServletRequest request, ServletResponse response);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 进行ant匹配  true 执行具体的拦截逻辑 false  跳过
        if (this.antMatch(request)) {
            this.internalHandler(request, response);
        }
        chain.doFilter(request, response);
    }


    private boolean antMatch(ServletRequest request) {
        Set<String> urlPatterns = getUrlPatterns();

        if (!CollectionUtils.isEmpty(urlPatterns)) {
            //进行Ant匹配处理
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            String uri = httpServletRequest.getRequestURI();
            Optional<String> any = urlPatterns.stream().filter(s -> {
                AntPathMatcher antPathMatcher = new AntPathMatcher();
                return antPathMatcher.match(s, uri);
            }).findAny();

            return any.isPresent();
        }
        // 如果 没有元素 表示全部匹配
        return true;
    }


    public Set<String> getUrlPatterns() {
        return urlPatterns;
    }
}
